package com.yunfeng.supercall.activity;

import java.util.Collections;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;

import com.lin.activity.PersonalDetailCardActivity;
import com.lin.utils.Parameters;
import com.lin.utils.Session;
import com.lin.utils.Session.ResultReceiver;
import com.ly.quickdev.library.adapter.ListBaseAdapter.ViewHolder;
import com.ly.quickdev.library.utils.JsonUtils;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.yunfeng.supercall.R;
import com.yunfeng.supercall.app.AppContext;
import com.yunfeng.supercall.bean.NewSuperFriendsBean;
import com.yunfeng.supercall.bean.SuperFriendsBean;
import com.yunfeng.supercall.bean.UserBean;
import com.yunfeng.supercall.httputils.MyAjaxCallBack;
import com.yunfeng.supercall.manager.ManagerFactory;
import com.yunfeng.supercall.manager.PushManager;

public class NewSuperFriendsListActivity extends
BaseStickyHeaderListActivity<NewSuperFriendsBean> {

	UserBean mUser;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setTitleBar(R.string.new_friend);
		mUser = getUser(getActivity());
		findView(R.id.side_bar).setVisibility(View.GONE);
		options = new DisplayImageOptions.Builder()
		.displayer(new RoundedBitmapDisplayer(this.getResources().getDimensionPixelOffset(R.dimen.corners_avatar)))
		.showImageOnFail(R.drawable.default_avatar)
		.showImageOnLoading(R.drawable.default_avatar)
		.cacheInMemory(true)
		.cacheOnDisk(true)
		.considerExifParams(true)
		.bitmapConfig(Bitmap.Config.RGB_565)
		.build();
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		// TODO Auto-generated method stub

	}

	@Override
	public void loadData() {
		// TODO Auto-generated method stub
		JSONObject json = getBaseParams(getActivity());
		try {
			json.put("i_pagenum", 0);
			mHttpClient.post(FUNCTION_GET_FRIEND_APPLY_LIST, json,
					new MyAjaxCallBack() {

				@Override
				public void onReceiveError(String msg, String errorCode) {
					// TODO Auto-generated method stub

				}

				@Override
				public void onReceiveData(String data, String msg) {
					// TODO Auto-generated method stub
					mList = JsonUtils.parseList(data,
							NewSuperFriendsBean.class);
					setListAdapter();
				}
			});
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	DisplayImageOptions options;
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		if (convertView == null) {
			convertView = getLayoutInflater().inflate(
					R.layout.list_item_new_friends, null);
		}
		final TextView state = ViewHolder.get(convertView, R.id.status);
		final NewSuperFriendsBean mFriends = mList.get(position);
		final TextView name = ViewHolder.get(convertView, R.id.tv);
		final ImageView img = ViewHolder.get(convertView, R.id.iv);
		if (mUser.getUserid() == mFriends.getUserid()) {
			ImageLoader.getInstance().displayImage(Parameters.SERVER_PIC_URL + mFriends.getOtherphoto(), img, options);
			name.setText(mFriends.getOthername());
			switch (mFriends.getState()) {
			case 0:
				state.setText(R.string.status_applying);
				break;
			case 1:
				state.setText(R.string.status_passed);
				break;
			case 2:
				state.setText(R.string.status_refused);
				break;
			}
			state.setBackgroundResource(android.R.color.transparent);
			state.setOnClickListener(null);
			convertView.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					
					SuperFriendsBean mSuperFriendsBean = new SuperFriendsBean();
					mSuperFriendsBean.setUserid(mFriends.getOtherid());
					mSuperFriendsBean.setPhone(mFriends.getOtherphone());
					mSuperFriendsBean.setPhoto(mFriends.getOtherphoto());
					mSuperFriendsBean.setNick_name(mFriends.getOthername());
					
					Intent intent = new Intent(NewSuperFriendsListActivity.this, PersonalDetailCardActivity.class);
					intent.putExtra(KEY_DATA, mSuperFriendsBean);
					startActivity(intent);
				}
			});
		} else {
			ImageLoader.getInstance().displayImage(Parameters.SERVER_PIC_URL + mFriends.getUserphoto(), img, options);
			name.setText(mFriends.getUsername());
			convertView.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					
					
					SuperFriendsBean mSuperFriendsBean = new SuperFriendsBean();
					
					mSuperFriendsBean.setUserid(mFriends.getUserid());
					mSuperFriendsBean.setPhone(mFriends.getPhone());
					mSuperFriendsBean.setPhoto(mFriends.getUserphoto());
					mSuperFriendsBean.setNick_name(mFriends.getUsername());
					
					
					Intent intent = new Intent(NewSuperFriendsListActivity.this, PersonalDetailCardActivity.class);
					intent.putExtra(KEY_DATA, mSuperFriendsBean);
					startActivity(intent);
				}
			});
			if (mFriends.getState() == 0) {
				state.setText(R.string.agree);
				//state.setBackgroundResource(R.color.main_green);
				state.setBackgroundResource(R.drawable.bg_button_green);
				state.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						agree(mFriends.getId(), (TextView) v,
								mFriends.getPhone(), mFriends.getOtherphone());
						// agree(mFriends.getOtherid());
					}
				});
			} else {
				state.setText(R.string.agreed);
				state.setBackgroundResource(android.R.color.transparent);
				state.setOnClickListener(null);
			}
		}

		return convertView;
	}

/*	SuperFriendsBean convertSuperFriend(NewSuperFriendsBean mFriends) {
		
		return mSuperFriendsBean;
		
	}*/
	
	private void agree(int userId, final TextView v, final String otherPhone, final String otherPhone2) {
		sendBroadcast(new Intent(ACTION_NEWFRIEND_MSG));
		JSONObject json = getBaseParams(getActivity());
		try {
			json.put("i_apyid", userId);
			json.put("i_state", 1);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		showProgressDialog(R.string.submiting);
		mHttpClient.post(FUNCTION_ACCEPT_FRIENDS, json, new MyAjaxCallBack() {

			@Override
			public void onReceiveError(String msg, String errorCode) {
				// TODO Auto-generated method stub


				showToast(msg);
				cancelProgressDialog();
			}

			@Override
			public void onReceiveData(String data, String msg) {
				// TODO Auto-generated method stub
				Session mSession = Session.getSession();
				mSession.init(getApplicationContext(), true);
				String phone = otherPhone;
				/*if(TextUtils.isEmpty(otherPhone)) {
					phone = otherPhone2;
				}*/
				mSession.SendPushMsg(getApplicationContext(), mUser.getNick_name() +"同意了您的好友请求" , 1, phone, mUser.getNick_name() +"同意了您的好友请求", new ResultReceiver<Integer>() {

					@Override
					public void onResult(boolean last, Integer args) {
						// TODO Auto-generated method stub

					}

				});

				showToast(R.string.agreed);
				v.setText(R.string.agreed);
				v.setBackgroundResource(android.R.color.transparent);
				v.setOnClickListener(null);
				PushManager.startPush(
						PushManager.TYPE_ADD_FRIEND,
						getString(R.string.apply_has_been_passed,
								mUser.getNick_name()), "", otherPhone);
				loadSuperFriend();
				cancelProgressDialog();
			}
		});
	}

	private List<SuperFriendsBean> mRealFriends;

	/**
	 * 加载所有的好友
	 */
	public void loadSuperFriend() {
		JSONObject json = BaseActivity.getBaseParams(getActivity());
		try {
			json.put("i_pagenum", 0);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		mHttpClient.post(FUNCTION_GET_FRIEND_LIST, json, new MyAjaxCallBack() {

			@Override
			public void onReceiveData(String data, String msg) {
				// TODO Auto-generated method stub
				mRealFriends = JsonUtils.parseList(data, SuperFriendsBean.class);
				Collections.sort(mRealFriends);
				ManagerFactory.createManager(SuperFriendsBean.class).saveList(
						mRealFriends);
			}

			@Override
			public void onReceiveError(String msg, String errorCode) {
				// TODO Auto-generated method stub
			}
		});
	}

}
